from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from django.urls import reverse
from .. import models
from . import cate_views, user_views


# 添加
def addgoods(request):
    # 查询所有的分类  进行返回
    types = cate_views.tab()
    return render(request, 'myadmin/goods/addgoods.html', {'types': types})


# 添加数据
def goodsinsert(request):
    # 接受用户的信息
    ginfo = request.POST.dict()
    ginfo.pop('csrfmiddlewaretoken')
    print(ginfo)

    file = request.FILES.get('g_url')
    if not file:
        return HttpResponse('<script>alert("请选择图片");history.back(-1)</script>')

    # 调图片上传
    g_url = user_views.upload(file)

    # 入库
    goods = models.Goods()
    goods.title = ginfo['title']
    goods.ordernum = ginfo['ordernum']
    goods.g_url = g_url
    goods.price = ginfo['price']
    goods.ginfo = ginfo['ginfo']
    goods.cateid = models.Cates.objects.get(id=ginfo['cateid'])
    goods.save()

    # 返回
    return HttpResponse('ok')


def goodslist(request):
    goods = models.Goods.objects.all()

    return render(request, 'myadmin/goods/list.html', {'goods': goods})
